package mynet

import (
	"fmt"
	"net"
)

const lenthByte = 8

func ServeOne() error {
	listen, err := net.Listen("tcp", "localhost:8080")
	if err != nil {
		return err
	}
	fmt.Println("server running------")
	for {
		conn, err := listen.Accept()
		if err != nil {
			return err
		}
		bs := make([]byte, lenthByte)
		_, err = conn.Read(bs)
		if err != nil {
			return err
		}
		fmt.Printf("接收客户端数据:%s", string(bs))
		fmt.Println()
		temp := make(chan int, 1)
		temp <- 1
		go func() {
			c := <-temp
			fmt.Println("-----server response------")
			fmt.Println(c)
			ws := []byte("success")
			_, err = conn.Write(ws)
			if err != nil {
				fmt.Println(err)
			}
		}()
	}
	return nil
}

func handleConnV1(listen net.Listener) error {
	for {
		//接收客户端请求并且读取请求数据
		conn, err := listen.Accept()
		if err != nil {
			return err
		}
		bs := make([]byte, lenthByte)
		_, err = conn.Read(bs)
		if err != nil {
			return err
		}
		fmt.Printf("接收客户端数据:%s", string(bs))
		fmt.Println()
		//响应客户端请求数据
		go func() {
			ws := []byte("success")
			_, err = conn.Write(ws)
			if err != nil {
				fmt.Println(err)
			}
		}()
	}
}
